import re
from datetime import datetime

class IDCard:
    def __init__(self,card_type=-1, name="", id_number="", gender="", birthdate="",ethnic="", address="",valid_date_start="",valid_date_end="",valid=False):
        self.card_type = card_type
        self.name = name
        self.id_number = id_number
        self.gender = gender
        self.birthdate = birthdate
        self.address = address
        self.ethnic = ethnic
        self.valid_date_start = valid_date_start
        self.valid_date_end = valid_date_end
        self.valid = valid
        self.check_uid = ""

    def to_dict(self):
        if self.card_type==0:
            return {
                'type': 0,
                'name': self.name,
                'id_number': self.id_number,
                'gender': self.gender,
                'birthdate': self.birthdate,
                'ethnic': self.ethnic,
                'address': self.address,
                'check_uid':self.check_uid,
                'valid':self.valid
            }
        if self.card_type==1:
            start_date = datetime.strptime(self.valid_date_start, '%Y-%m-%d').strftime('%Y.%m.%d')
            end_date = datetime.strptime(self.valid_date_end, '%Y-%m-%d').strftime('%Y.%m.%d')
            validity = start_date+"-"+end_date
            return {
                'type': 1,
                'valid_date_start': self.valid_date_start,
                'valid_date_end': self.valid_date_end,
                "validity" : validity,
                'check_uid': self.check_uid,
                'valid': self.valid
            }
        return ""




class IdCardInfo:
    def __init__(self, id_card_number):
        self.id_card_number = id_card_number
        self.birthday = None
        self.gender = None
        self.ethnic = None
        self.extract_info()

    def extract_info(self):
        # 提取出生日信息
        birthday_pattern = r"(?<=\d{6})\d{8}"
        birthday_match = re.search(birthday_pattern, self.id_card_number)
        if birthday_match:
            birthday_str = birthday_match.group(0)
            year = birthday_str[:4]
            month = birthday_str[4:6]
            day = birthday_str[6:]
            self.birthday = f"{year}-{month}-{day}"

        # 提取性别信息
        gender_pattern = r"(?<=\d{16})\d|\d(?=X)"
        gender_match = re.search(gender_pattern, self.id_card_number)
        if gender_match:
            gender_code = int(gender_match.group(0))
            if gender_code % 2 == 0:
                self.gender = "女"
            else:
                self.gender = "男"

        # 提取民族信息
        ethnic_pattern = r"(?<=\d{2})\d{2}(?=)"
        ethnic_match = re.search(ethnic_pattern, self.id_card_number)
        if ethnic_match:
            ethnic_code = int(ethnic_match.group(0))
            self.ethnic = get_ethnic_name(ethnic_code)



def get_ethnic_name(code):
    # 根据民族编码获取民族名称
    ethnic_dict = {0: "汉族", 1: "蒙古族", 2: "回族", 3: "藏族", 4: "维吾尔族",
                   5: "苗族", 6: "彝族", 7: "壮族", 8: "布依族", 9: "朝鲜族",
                   10: "满族", 11: "侗族", 12: "瑶族", 13: "白族", 14: "土家族",
                   15: "哈尼族", 16: "哈萨克族", 17: "傣族", 18: "黎族", 19: "傈僳族",
                   20: "佤族", 21: "畲族", 22: "高山族", 23: "拉祜族", 24: "水族",
                   25: "东乡族", 26: "纳西族", 27: "景颇族", 28: "柯尔克孜族", 29: "土族",
                   30: "达斡尔族", 31: "仫佬族", 32: "羌族", 33: "布朗族", 34: "撒拉族",
                   35: "毛南族", 36: "仡佬族", 37: "锡伯族", 38: "阿昌族", 39: "普米族",
                   40: "塔吉克族", 41: "怒族", 42: "乌孜别克族", 43: "俄罗斯族", 44: "鄂温克族",
                   45: "德昂族", 46: "保安族", 47: "裕固族", 48: "京族", 49: "塔塔尔族",
                   50: "独龙族", 51: "鄂伦春族", 52: "赫哲族", 53: "门巴族", 54: "珞巴族",
                   55: "基诺族"}
    if code in ethnic_dict:
        return ethnic_dict[code]
    else:
        return None

def extract_date_from_string(string):
    # 使用正则表达式匹配日期信息
    pattern = re.compile(r'(\d{4})年(\d{1,2})月(\d{1,2})日')
    match = pattern.search(string)

    if match:
        # 获取匹配的年、月、日
        year = int(match.group(1))
        month = int(match.group(2))
        day = int(match.group(3))

        # 使用 datetime 模块创建日期对象
        date_obj = datetime(year, month, day)

        return date_obj
    else:
        return None


def extract_id_card_number(input_str):
    pattern = r"\d{17}[\dX]"
    match = re.search(pattern, input_str)
    if match:
        return match.group(0)
    else:
        return None


def check_idcard(idcard):
    """
    检查身份证号码的合法性
    """
    # 判断身份证号码的长度是否正确
    if len(idcard) != 18:
        return False

    # 判断身份证号码前17位是否都为数字
    if not idcard[:17].isdigit():
        return False

    # 判断身份证号码最后一位是否为数字或字母（X）
    if not idcard[-1].isdigit() and idcard[-1].upper() != 'X':
        return False

    # 计算身份证号码的校验码
    factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    checkcode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
    check_sum = sum(int(idcard[i]) * factor[i] for i in range(17))
    remainder = check_sum % 11
    if idcard[-1].upper() != checkcode[remainder]:
        return False

    return True


def extract_valid_date(text):
    # 定义正则表达式
    date_pattern = r"\d{4}\.\d{2}\.\d{2}"

    # 使用正则表达式查找日期
    dates = re.findall(date_pattern, text)

    # 如果找到两个日期，则将第一个日期作为签发日期的开始时间，将第二个日期作为签发日期的结束时间
    if len(dates) == 2:
        start_date = datetime.strptime(dates[0], '%Y.%m.%d').strftime('%Y-%m-%d')
        end_date = datetime.strptime(dates[1], '%Y.%m.%d').strftime('%Y-%m-%d')
        return start_date, end_date
    else:
        return None